package com.lebronxin.leojcodesandbox.controller;

import cn.hutool.http.HttpRequest;
import com.lebronxin.leojcodesandbox.JavaNativeCodeSandbox;
import com.lebronxin.leojcodesandbox.model.ExecuteCodeRequest;
import com.lebronxin.leojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @version 1.0
 * @authpr 陈鑫
 */
@RestController("/")
public class MainController {

    //定义鉴权请求头和密钥
    public static final String AUTH_REQUEST_HEADER = "auth";

    public static final String AUTH_REQUEST_SECRET = "secretKey";

    @Resource
    private JavaNativeCodeSandbox javaNativeCodeSandbox;

    @GetMapping("/health")
    public String healthCheck(){
        return "ok";
    }

    /**
     * 代码沙箱开放API
     * @param executeCodeRequest
     * @return
     */
    @PostMapping("/executeCode")
    public ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request, HttpServletResponse response){

        //基本的认证
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        if (!AUTH_REQUEST_SECRET.equals(authHeader)){
            response.setStatus(403);
            return null;
        }

        if (executeCodeRequest == null){
            throw new RuntimeException("请求参数为空");
        }

        //这里使用的原生代码沙箱，项目上线要改用Docker实现的代码沙箱
        return javaNativeCodeSandbox.executeCode(executeCodeRequest);
    }
}
